<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Episode;
use App\Models\History;
use App\Models\Like;
use App\Models\Task;
use App\Models\TaskLog;
use App\Models\Video;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class LikesController extends Controller
{
    /***
     *我的喜欢列表
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request,Like $like)
    {
        $ep = $this->user->like()->select('likes.sort_id as looking')->orderByDesc('likes.updated_at')->paginate(10);
        if($ep->isEmpty()){
            return $this->error('没有喜欢记录');
        }
        $ep=$ep->toArray();
        foreach ($ep['data'] as &$item){
            $item['cover']=dealUrl($item['cover']);
            $item['cover_crosswise'] = dealUrl($item['cover_crosswise']);
            $uplist=Video::where('episodes_id',$item['id'])->max('sort');
            $item['uplist']=empty($uplist)?0:$uplist;
        }
        return $this->success('success',$ep);
    }


    /***
     * 添加喜欢
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request,Like $like)
    {
        if(empty($this->user)){
            return  $this->error('未登录');
        }
        $ep=Episode::find($request->id);
        if(empty($ep)){
            return  $this->error('该剧不存在');
        }
        $data=[
            'user_id'=>$this->user->id,
            'sort_id'=>$request->sort_id,
            'episodes_id'=>$request->id,
        ];
        $start_time = Carbon::now()->startOfDay()->toDateTimeString();
        $end_time = Carbon::now()->endOfDay()->toDateTimeString();
        $task = Task::find(6);
        $taskLogCount = TaskLog::where(['user_id' => $this->user->id, 'task_id' => $task->id])->whereBetween('created_at', [$start_time, $end_time])->count();
//        dd($taskLogCount);
        if ($taskLogCount <= $task->require) {
            TaskLog::add($this->user->id, $task->id, $task->price);
        }
        $is_cun=$like->updateOrCreate($data,$data);
        return $this->success('success',$is_cun);
    }

    /***
     * 删除喜欢
     * @param Like $like
     * @return \Illuminate\Http\JsonResponse
     */
    public function rezuiju(Like $like)
    {
//            $ret=$like->where('user_id',$this->user->id)->delete();//软删除
            $ret=$like->where('user_id',$this->user->id)->forceDelete();//软删除
//        $ret=$like->where('user_id',$this->user->id)->restore();//恢复软删除
            if($ret){
                return $this->success('删除成功');
            }else{
                return $this->error('删除失败');
            }
    }
}
